package gbench.sandbox.record;

import static gbench.common.tree.LittleTree.cph2;
import gbench.common.tree.LittleTree.IRecord;
import java.util.stream.*;
import java.util.*;

import org.junit.jupiter.api.Test;

public class JunitGroupBy {

    @Test
    public void foo() {
        final var digits = "0123456789".split("");
        final var aa = cph2(digits, digits, digits, digits, digits, digits)
        .collect(Collectors.groupingBy(e -> e.get("0")));
        System.out.println(aa.keySet());
    }

    @Test
    public void bar() {
        final var digits = "0123456789".split("");
        final var qq = cph2(digits, digits, digits, digits, digits, digits)
        .collect(Collector.of(() -> new HashMap<String, LinkedList<IRecord>>(), (aa, a) -> {
            final var key = a.str("0");
            final var vv = aa.computeIfAbsent(key, t -> new LinkedList<>());
            vv.add(a);
        }, (aa, bb) -> {
            bb.forEach((k, ss) -> {
                aa.merge(k, ss, (p, q) -> {
                    p.addAll(q);
                    return p;
                });
            });
            return aa;
        }));
        System.out.println(qq.keySet());
    }

    @Test
    public void qux() {// 性能最差
        final var digits = "0123456789".split("");
        final var qq = cph2(digits, digits, digits, digits, digits)
        .collect(Collector.of(() -> new HashMap<String, Stream<IRecord>>(), (mm, rec) -> {
            mm.compute(rec.str("0"),
                    (k, stream) -> stream == null ? Stream.of(rec) : Stream.concat(stream, Stream.of(rec)));
        }, (m1, m2) -> {
            m2.forEach((key, stream2) -> {
                m1.compute(key, (k, stream1) -> stream1 == null ? stream2 : Stream.concat(stream1, stream2));
            });
            return m1;
        }));
        System.out.println(qq.keySet());
    }

}
